package com.hk.web.core.config.asyn;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@EnableScheduling //开启spring-task支持
@EnableAsync
@Configuration
@Order(2)
@ComponentScan(basePackages = {"com.hk.**.async","com.hk.**.task.**"})
public class AsyncExecutorConfig implements SchedulingConfigurer,AsyncConfigurer {
    private static final Logger LOGGER = LoggerFactory.getLogger(AsyncExecutorConfig.class);


    @Override
    public Executor getAsyncExecutor() {
        //spring异步线程池配置
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(20);//核心异步线程数
        executor.setMaxPoolSize(50);//最大异步线程数
        executor.setKeepAliveSeconds(30);
        executor.setQueueCapacity(50);//异步线程池所使用的缓冲队列
        executor.setThreadNamePrefix("HkAsync-");//异步线程名称前缀
        executor.setWaitForTasksToCompleteOnShutdown(true);//当调度器shutdown被调用时等待当前被调度的任务完成
        executor.setAwaitTerminationSeconds(60);//设置等待时间
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//拒绝策略 当线程队列满了 会由掉用线程来执行该任务
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new MyAsyncUncaughtExceptionHandler();
    }

    /**
     * 自定义异步线程异常处理类
     */
    class MyAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {

        //手动处理捕获的异常
        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
            LOGGER.error("异步线程异常信息：{}，方法名：{}，方法参数：{} ", throwable.getMessage(), method.getName(), obj);
        }
    }
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
    }

    @Bean(destroyMethod = "shutdown")
    public Executor taskExecutor() {
        //spring任务线程池配置
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(20);//设置任务线程数
        scheduler.setThreadNamePrefix("HkTask-");//任务线程名称前缀
        scheduler.setWaitForTasksToCompleteOnShutdown(true);//当调度器shutdown被调用时等待当前被调度的任务完成
        scheduler.setAwaitTerminationSeconds(90);//设置等待时间
        //设置当任务被取消的同时从当前调度器移除的策略
        scheduler.setRemoveOnCancelPolicy(true);
        return scheduler;
    }
}
